package com.alliky.home.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alliky.core.base.Fragment;
import com.alliky.core.entity.vo.BannerEntityInfo;
import com.alliky.core.entity.vo.CategoryVO;
import com.alliky.core.entity.vo.GoodsVO;
import com.alliky.core.log.KLog;
import com.alliky.core.net.ImageLoader;
import com.alliky.core.pay.PayListenerUtil;
import com.alliky.core.pay.PayResultListener;
import com.alliky.core.router.RoutePath;
import com.alliky.core.widget.RxToast;
import com.alliky.core.widget.TitleBar;
import com.alliky.home.R;
import com.alliky.home.R2;
import com.alliky.home.mvp.contract.HomeContract;
import com.alliky.home.mvp.presenter.HomePresenter;
import com.alliky.home.ui.activity.MyScanerKitActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.stx.xhb.xbanner.XBanner;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;
import static com.alibaba.sdk.android.tbrest.utils.Base64.DECODE;

@Route(path = RoutePath.Home.HOME_FRAGMENT)
public class HomeFragment extends Fragment<HomePresenter> implements HomeContract.View, PayResultListener {

    @BindView(R2.id.titleBar)
    TitleBar mTitleBar;

    @BindView(R2.id.xbanner)
    XBanner mXBanner;
    @BindView(R2.id.recyclerViewClassify)
    RecyclerView recyclerViewClassify;
    @BindView(R2.id.recyclerViewHot)
    RecyclerView recyclerViewHot;

    BaseQuickAdapter<CategoryVO, BaseViewHolder> mClassifyAdapter;
    BaseQuickAdapter<GoodsVO, BaseViewHolder> mHotAdapter;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private final int CAMERA_REQ_CODE = 0x01;
    private final int REQUEST_CODE_SCAN_ONE = 0x02;

    public HomeFragment() {
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void onInitView(Bundle savedInstanceState, View view) {
        PayListenerUtil.getInstance().addListener(this);
        mXBanner.loadImage(((banner, model, view1, position) -> {
            ImageLoader.load(((BannerEntityInfo) model).getBannerEntity().getThumb(), (ImageView) view1);
        }));
        initRecyclerViewClassify();
        initRecyclerViewHot();
        initRefreshData();
        mTitleBar.setRightIconOnClickListener(v -> {
//            requestPermission(CAMERA_REQ_CODE, DECODE);
//            ScanUtil.startScan(getActivity(), REQUEST_CODE_SCAN_ONE, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.CODABAR_SCAN_TYPE).create());
            startActivity(MyScanerKitActivity.class);
        });
    }

    private void requestPermission(int requestCode, int mode) {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (permissions == null || grantResults == null)
            return;
        if (grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (requestCode == CAMERA_REQ_CODE) {
            ScanUtil.startScan(getActivity(), REQUEST_CODE_SCAN_ONE, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void initRefreshData() {
        refreshLayout.setOnRefreshListener(refreshLayout1 -> {
            getHotGoods(true);
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> {
            getHotGoods(false);
        });
    }

    private void initRecyclerViewClassify() {
        recyclerViewClassify.setLayoutManager(new GridLayoutManager(getContext(), 5));
        recyclerViewClassify.setAdapter(mClassifyAdapter = new BaseQuickAdapter<CategoryVO, BaseViewHolder>(R.layout.item_home_category_layout) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, CategoryVO categoryVO) {
                ImageLoader.load(categoryVO.getThumb2(), holder.getView(R.id.iv_image));
                holder.setText(R.id.tv_name, categoryVO.getCate_name());
            }
        });
    }

    private void initRecyclerViewHot() {
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerViewHot.setLayoutManager(layoutManager);
        recyclerViewHot.setAdapter(mHotAdapter = new BaseQuickAdapter<GoodsVO, BaseViewHolder>(R.layout.item_home_hot_layout) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, GoodsVO goodsVO) {
//                ImageLoader.load(getContext(), goodsVO.getGoods_thumb(), holder.getView(R.id.iv_image));

                ImageLoader.load(goodsVO.getGoods_thumb(), holder.getView(R.id.iv_image));

                holder.setText(R.id.tv_name, goodsVO.getGoods_name());
                holder.setText(R.id.tv_price, "￥" + goodsVO.getMarket_price());
            }
        });
    }

    @Override
    public void onInitData() {
        getBanner();
        getCategory();
        getHotGoods(true);
    }

    private void getBanner() {
        HashMap params = new HashMap();
        params.put("type", 1);
        params.put("pageNum", 1);
        params.put("pageSize", 4);
        mPresenter.getBanner(params);
    }

    private void getCategory() {
        HashMap params = new HashMap();
        params.put("type", 1);
        params.put("pageNum", 1);
        params.put("pageSize", 4);
        mPresenter.getCategory(params);
    }

    private void getHotGoods(boolean isRefresh) {
        pageNum = isRefresh ? 1 : pageNum;
        HashMap params = new HashMap();
        params.put("type", 1);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        mPresenter.getHotGoods(params, isRefresh);
    }

    @Override
    public void finishRefresh() {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
    }

    @Override
    public void finishLoadMore() {
        if (refreshLayout != null) {
            refreshLayout.finishLoadMore();
        }
    }

    @Override
    public void showBannerResult(List<BannerEntityInfo> list) {
        mXBanner.setBannerData(list);
    }

    @Override
    public void showCategory(List<CategoryVO> list) {
        mClassifyAdapter.addData(list);
    }

    @Override
    public void showHotGoods(List<GoodsVO> list, boolean isRefresh) {
        mHotAdapter.addData(list);
    }

    @Override
    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    @Override
    public void onPaySuccess() {

    }

    @Override
    public void onPayError() {

    }

    @Override
    public void onPayCancel() {

    }

//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (data == null) {
//            return;
//        }
//        if ((requestCode == this.REQUEST_CODE_SCAN_ALL) && (resultCode == Activity.RESULT_OK)) {
//            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
//            if (obj != null && obj.getOriginalValue() != null) {
//                this.barcode = obj.getOriginalValue();
//            }
//        } else if ((requestCode == this.REQUEST_TAKE_PHOTO) && (resultCode == Activity.RESULT_OK)) {……}
//    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }


        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null) {
                KLog.d("code", " >>> " + obj.originalValue);
                RxToast.normal(obj.originalValue);
            }
        }
    }
}
